<!--
 * @Author: daidai
 * @Date: 2022-02-28 16:16:42
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2022-10-25 09:18:22
 * @FilePath: \web-pc\src\pages\big-screen\view\indexs\left-center.vue
-->
<template>
  <Echart
    id="leftCenter"
    :options="options"
    class="left_center_inner"
    v-if="pageflag"
    ref="charts"
  />
  <Reacquire v-else @onclick="processData" style="line-height: 200px">
    重新获取
  </Reacquire>
</template>

<script>
  export default {
    data() {
      return {
        options: {},
        leftTopData: {
          total: 0,
          reported: 0,
          unreported: 0,
          registrationRate: 0,
        },
        pageflag: true,
      };
    },
    props: {
      allStudentsData: {
        type: Object,
        default: () => ({}),
      },
      reportedStudentsData: {
        type: Object,
        default: () => ({}),
      },
    },
    watch: {
      reportedStudentsData: {
        handler(newData) {
          if (newData && Object.keys(newData).length > 0) {
            this.processData();
          }
        },
        immediate: true,
        deep: true,
      },
      allStudentsData: {
        handler(newData) {
          // 当报到数据不可用时，使用学生总览数据作为备用
          if (
            (!this.reportedStudentsData ||
              Object.keys(this.reportedStudentsData).length === 0) &&
            newData &&
            Object.keys(newData).length > 0
          ) {
            this.processData();
          }
        },
        immediate: true,
        deep: true,
      },
    },
    created() {
      this.processData();
    },
    methods: {
      processData() {
        this.pageflag = true;

        try {
          // 优先使用报到统计数据 - 现在直接是data字段的内容
          if (
            this.reportedStudentsData &&
            this.reportedStudentsData.overallStats
          ) {
            const overallStats = this.reportedStudentsData.overallStats;

            // 从数据中提取统计信息
            const totalStudents = overallStats.totalStudents || 0;
            const enrolledStudents = overallStats.enrolledStudents || 0;
            const notEnrolledStudents = overallStats.notEnrolledStudents || 0;
            const enrollmentRate = overallStats.overallEnrollmentRate || 0;

            this.leftTopData = {
              total: totalStudents,
              reported: enrolledStudents,
              unreported: notEnrolledStudents,
              registrationRate: enrollmentRate,
            };

            console.log("处理后的总览数据:", this.leftTopData);
          } else {
            console.warn("报到统计数据不可用，使用备用数据");
            this.handleFallbackData();
          }

          this.$nextTick(() => {
            this.init();
          });
        } catch (error) {
          console.error("处理报到统计数据失败:", error);
          this.handleFallbackData();
        }
      },

      // 处理备用数据逻辑
      handleFallbackData() {
        // 如果接口失败，尝试使用传入的学生总览数据
        if (this.allStudentsData && this.allStudentsData.response_info) {
          console.log("使用备用学生总览数据:", this.allStudentsData);

          const totalStudents =
            this.allStudentsData.response_info.total_students || 0;

          this.leftTopData = {
            total: totalStudents,
            reported: 0, // 接口失败时默认为0
            unreported: totalStudents,
            registrationRate: 0,
          };
        } else {
          console.log("使用默认数据");
          this.leftTopData = {
            total: 0,
            reported: 0,
            unreported: 0,
            registrationRate: 0,
          };
        }

        this.$nextTick(() => {
          this.init();
        });
      },

      init() {
        // 动态计算总数，避免全为0时饼图无法显示
        const hasData =
          this.leftTopData.reported > 0 || this.leftTopData.unreported > 0;

        // 根据报到情况调整颜色
        let colors = ["#56B557", "#FF6B6B"]; // 绿色表示已报到，红色表示未报到

        // 如果没有人报到，使用更醒目的颜色
        if (
          this.leftTopData.reported === 0 &&
          this.leftTopData.unreported > 0
        ) {
          colors = ["#FFA726", "#FF6B6B"]; // 橙色和红色，更醒目
        }

        // 构建饼图数据
        let pieData = [];
        if (this.leftTopData.reported > 0) {
          pieData.push({
            value: this.leftTopData.reported,
            name: "已报到人数",
            itemStyle: { color: colors[0] },
          });
        }
        if (this.leftTopData.unreported > 0) {
          pieData.push({
            value: this.leftTopData.unreported,
            name: "未报到人数",
            itemStyle: { color: colors[1] },
          });
        }

        // 如果没有任何数据，显示占位数据
        if (pieData.length === 0) {
          pieData = [
            {
              value: 1,
              name: "暂无数据",
              itemStyle: { color: "#666666" },
            },
          ];
        }

        let pieconfig = {
          name: "报到总览",
          type: "pie",
          radius: ["42%", "65%"],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 4,
            borderColor: "rgba(0,0,0,0.1)",
            borderWidth: 2,
          },
          data: pieData,
        };

        this.options = {
          title: {
            text: [
              "{value|" + this.leftTopData.total + "}",
              "{name|总数}",
              "{rate|报到率: " +
                this.leftTopData.registrationRate.toFixed(1) +
                "%}",
            ].join("\n"),
            top: "center",
            left: "center",
            textStyle: {
              rich: {
                value: {
                  color: "#ffffff",
                  fontSize: 24,
                  fontWeight: "bold",
                  lineHeight: 20,
                },
                name: {
                  color: "#ffffff",
                  lineHeight: 16,
                  fontSize: 12,
                },
                rate: {
                  color:
                    this.leftTopData.registrationRate > 50
                      ? "#56B557"
                      : this.leftTopData.registrationRate > 0
                      ? "#FFA726"
                      : "#FF6B6B",
                  lineHeight: 18,
                  fontSize: 13,
                  fontWeight: "bold",
                },
              },
            },
          },
          tooltip: {
            trigger: "item",
            backgroundColor: "rgba(0,0,0,.8)",
            borderColor: "rgba(147, 235, 248, .8)",
            textStyle: {
              color: "#FFF",
            },
            formatter: function (params) {
              if (params.name === "暂无数据") {
                return "暂无报到数据";
              }
              const total = this.leftTopData.total;
              const rate =
                total > 0 ? ((params.value / total) * 100).toFixed(1) : 0;
              return `${params.name}<br/>${params.value}人 (${rate}%)`;
            }.bind(this),
          },
          legend: {
            show: false,
          },
          series: [pieconfig],
        };
      },
    },
  };
</script>

<style lang="scss" scoped>
  .left_center_inner {
    width: 100%;
    height: 100%;
  }
</style>
